package com.yingxin.yxerp.module.dingtalk.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yingxin.yx.framework.commons.constant.CommonConst;
import com.yingxin.yx.framework.commons.exception.BizException;
import com.yingxin.yxerp.module.dingtalk.config.WeComAppConfig;
import com.yingxin.yxerp.module.dingtalk.constant.WeComUrlConstant;
import com.yingxin.yxerp.module.dingtalk.dto.WeComUserDepartmentResultListDto;
import com.yingxin.yxerp.module.dingtalk.dto.WeComUserDto;
import com.yingxin.yxerp.module.dingtalk.dto.WeComUserListDto;
import com.yingxin.yxerp.module.dingtalk.service.IWeComDeptBaseService;
import com.yingxin.yxerp.module.dingtalk.service.IWeComUserService;
import com.yingxin.yxerp.module.dingtalk.util.WeComAccessTokenUtil;
import com.yingxin.yxerp.module.dingtalk.vo.WeComDeptBaseRespVo;
import com.yingxin.yxerp.module.dingtalk.vo.WeComUserRespVo;
import com.yingxin.yxerp.module.dingtalk.vo.req.WeComReqVo;
import com.yingxin.yxerp.module.dingtalk.vo.we.com.WeComUserDepartmentIdList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WeComUserServiceImpl implements IWeComUserService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WeComAppConfig appConfig;

    @Autowired
    private WeComAccessTokenUtil weComAccessTokenUtil;

    @Autowired
    private IWeComDeptBaseService weComDeptBaseService;

    private HttpHeaders setRestTemplate(){
        HttpHeaders headers = new HttpHeaders();
        MediaType mediaType = new MediaType(
                "application", "json", Charset.forName("UTF-8") );
        headers.setContentType( mediaType );
        headers.setAccept( Collections.singletonList( MediaType.APPLICATION_JSON_UTF8 ) );

        return headers;
    }

    /**
     * 获取成员,部门 ID列表
     */
    @Override
    public List<WeComUserDepartmentIdList> getUserIdList() {
        // 获取 AccessToken
        String accessToken = weComAccessTokenUtil.getAccessToken(
                appConfig.getAppCorpId(), appConfig.getAddressbookSecret() );

        WeComReqVo vo = new WeComReqVo();
        vo.setLimit(1000);

        String json = JSON.toJSONString( vo );

        HttpHeaders headers = setRestTemplate();

        HttpEntity<String> request = new HttpEntity<>( json, headers );

        ResponseEntity<String> response = restTemplate.postForEntity(
                WeComUrlConstant.POST_USER_LIST_URL+"?access_token="+accessToken, request, String.class );

        WeComUserDepartmentResultListDto dto =
                JSON.parseObject( response.getBody(), new TypeReference<WeComUserDepartmentResultListDto>(){} );

        if( dto.getErrcode().trim().equals( CommonConst.FALSE ) ){
            return dto.getDept_user();
        }else{
            throw new BizException( dto.getErrmsg() );
        }
    }

    /**
     * 根据用户 id 获取用户（通讯录）信息 - 非人事助手信息
     */
    @Override
    public WeComUserDto getByUserId(String userId){
        // 获取 AccessToken
        String accessToken = weComAccessTokenUtil.getAccessToken(
                appConfig.getAppCorpId(), appConfig.getAppSecret() );

        ResponseEntity<String> response = restTemplate.getForEntity(
                WeComUrlConstant.GET_USER_ID_URL+"?access_token="+accessToken+"&userid="+userId, String.class );

        WeComUserDto dto = JSON.parseObject( response.getBody(), new TypeReference<WeComUserDto>(){} );
        dto.setUserid( userId );

        if( dto.getErrcode().trim().equals( CommonConst.FALSE ) ){
            return dto;
        }else{
            throw new BizException( dto.getErrmsg() );
        }
    }

    /**
     * 获取所有员工的通讯录信息
     */
    @Override
    public List<WeComUserDto> getUserList(){
        List<WeComUserDepartmentIdList> userDepartmentIdLists = getUserIdList();
        List<WeComUserDto> userDtos = new ArrayList<>();

        // 用户id列表
        List<String> userIds = userDepartmentIdLists.stream().map( WeComUserDepartmentIdList::getUserid ).
                distinct().collect(Collectors.toList());
        if( CollectionUtil.isNotEmpty( userIds ) ){
            for( String userId : userIds ){
                WeComUserDto dto = getByUserId( userId );
                userDtos.add( dto );
            }
            return userDtos;
        }
        return null;
    }

    /**
     * 根据部门获取部门员工信息
     */
    @Override
    public List<WeComUserDto> getByDeptIdUserList(){
        List<WeComDeptBaseRespVo> deptBaseList = weComDeptBaseService.getDeptBaseList();
        List<String> deptIds = deptBaseList.stream().map( WeComDeptBaseRespVo::getId ).distinct().collect( Collectors.toList() );
        if( CollectionUtil.isEmpty( deptIds ) ){
            return null;
        }
        // 获取 AccessToken
        String accessToken = weComAccessTokenUtil.getAccessToken(
                appConfig.getAppCorpId(), appConfig.getAppSecret() );
        List<WeComUserDto> userDtos = new ArrayList<>();
        for( String deptId : deptIds ) {
            ResponseEntity<String> response = restTemplate.getForEntity(
                    WeComUrlConstant.GET_DEPT_USER_LIST_URL + "?access_token=" + accessToken + "&department_id="+deptId, String.class);
            WeComUserListDto dto = JSON.parseObject( response.getBody(), new TypeReference<WeComUserListDto>(){} );
            if( dto.getErrcode().trim().equals( CommonConst.FALSE ) ){
                userDtos.addAll( dto.getUserlist() );
            }
        }
        return userDtos;
    }

    /**
     * 获取人事助手所有员工信息
     */
    @Override
    public List<WeComUserRespVo> getPersonnelAssistantList(){
        List<WeComUserDepartmentIdList> userDepartmentIdLists = getUserIdList();
        List<String> userIds = userDepartmentIdLists.stream().map( WeComUserDepartmentIdList::getUserid ).
            distinct().collect(Collectors.toList());

        // List<String> userIds = new ArrayList<>();
        // userIds.add( "d41d8cd98f00b204e9800998ecf8427e" );

        List<WeComUserRespVo> userRespVos = new ArrayList<>();

        // 获取 AccessToken
        String accessToken = weComAccessTokenUtil.getAccessToken(
                appConfig.getAppCorpId(), appConfig.getAppSecret() );

        // 请求条件
        WeComReqVo vo = new WeComReqVo();
        vo.setGet_all( true );

        for( String userId : userIds ){
            vo.setUserid( userId );
            String json = JSON.toJSONString( vo );
            HttpHeaders headers = setRestTemplate();
            HttpEntity<String> request = new HttpEntity<>( json, headers );
            ResponseEntity<String> response = restTemplate.postForEntity(
                    WeComUrlConstant.POST_EMPLOYEE_ROSTER_LIST_URL+"?access_token="+accessToken, request, String.class );
            WeComUserRespVo dto = JSON.parseObject( response.getBody(), new TypeReference<WeComUserRespVo>(){} );

            if( dto.getErrcode().trim().equals( CommonConst.FALSE ) ){
                dto.setUserid( userId );
                userRespVos.add( dto );
            }else{
                throw new BizException( dto.getErrmsg() );
            }
        }

        return userRespVos;
    }

}
